﻿ using Common;
using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.Market;
using NB.MGJ.Service.Config;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xfrog.Net;


namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 机构管理相关
    /// </summary>
    /// =======================================================================
    /// 类名：ManagerController ManagerController的备注：ManagerController~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/8/16        段扬             新建<br/>
    /// =======================================================================<br/>
    public partial class MarketController 
    {
        JsonHelper jsonHelper = new JsonHelper();
        DBHService _dbh = new DBHService();
        ConfigManagerService _configManager = new ConfigManagerService();
        TheWinningService _the = new TheWinningService();
        #region 奖池

        #region 分页

        /// <summary>
        /// 分页 红包
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">显示行数</param>
        /// <param name="sortField">排序字段</param>
        /// <param name="sortOrder">升 降 序</param>
        /// <param name="key">查询条件</param>
        /// <param name="search">详细查询条件</param>
        /// <returns></returns>
        public JsonResult JackpotTable(int pageIndex, int pageSize, string sortField, string sortOrder, string key, string search, string type)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = sortField + " " + sortOrder;
            pm.StrCondition = " type=" + type + "  and enterpriseID=" + LogOnUser.EnterpriseId+" and ViewDel=0";
            if (!string.IsNullOrEmpty(search)) pm.StrCondition += " and name like '%" + search + "%'";
            var list = _market.GetJackpotPager(ref pm);
            return Json(list);
        }

        #endregion

        #region 奖池统计发放数据

        /// <summary>
        /// 获取  当月 当日 奖池发送数量和金额 根据日期
        /// </summary>
        /// <param name="type">奖池类型 类型1红包2优惠券3流量包</param>
        /// <returns></returns>
        public JsonResult GetJackpotSendNum(int type)
        {
            string monthMoney = "0.00";
            string monthCount = "0";
            string dayMoney = "0.00";
            string dayCount = "0";
            if (_dbh.TabExists("marketing", "marketing_thewinning" + LogOnUser.ECode))
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                DataTable monthDt = _market.GetJackpotSendNum(type, date.ToString().Substring(0, 7), LogOnUser.ECode);
                  monthMoney = monthDt.Rows[0]["money"].ToString();
                  monthCount = monthDt.Rows[0]["count"].ToString();
                DataTable dayDt = _market.GetJackpotSendNum(type, date.Substring(0, 10), LogOnUser.ECode);
                  dayMoney = dayDt.Rows[0]["money"].ToString();
                  dayCount = dayDt.Rows[0]["count"].ToString();
            }
           
            return Json(new { monthMoney = monthMoney, monthCount = monthCount, dayMoney = dayMoney, dayCount = dayCount });
        }

        /// <summary>
        /// 获取奖池发送数量 和金额  根据日期获取
        /// </summary>
        /// <param name="type">类型 1红包2优惠券3流量包</param>
        /// <param name="dayNum">天数</param>
        /// <returns></returns>
        public JsonResult GetJackpotSendNumList(int jID, int type, int dayNum)
        {
            return Json(_market.GetJackpotSendNumList(jID, type, dayNum, LogOnUser.ECode));
        }

        /// <summary>
        /// 获取发放金额 和数量  根据奖池ID
        /// </summary>
        /// <param name="jId">奖池ID</param>
        /// <returns></returns>
        public JsonResult GetJackpotSendResidue(int jId)
        {
            Marketing_Jackpot j = _market.GetJackpotModel(jId);
            decimal TotalMoney = j.TotalMoney;
            int? TotalNums = j.TotalNums;
            string sendMoney = "0.00";
            string sendCount = "0";
            if (_dbh.TabExists("marketing", "marketing_thewinning" + LogOnUser.ECode))
            {
                       DataRow dr = _market.GetJackpotSendResidue(jId, LogOnUser.ECode).Rows[0];
                       sendMoney = dr["sendMoney"].ToString();
                       sendCount = dr["sendCount"].ToString();

            }


            return Json(new { TotalMoney = TotalMoney, TotalNums = TotalNums, sendMoney = sendMoney, sendCount = sendCount }, JsonRequestBehavior.AllowGet);
        }


        #region 奖池关联活动

        /// <summary>
        /// 根据奖池ID 获取关联活动数据
        /// </summary>
        /// <param name="jId">奖池ID</param>
        /// <returns></returns>
        public JsonResult GetJackpot_ActivityTable(int pageIndex, int pageSize, string sortField, string sortOrder, int jId)
        {
            PagerModel pg = new PagerModel();
            pg.Page = pageIndex;
            pg.PageSize = pageSize;
            pg.StrCondition = "j.id=" + jId;
            return Json(_market.GetJackpot_Activity(ref pg), JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 用户中奖管理
        /// <summary>
        ///中奖明细
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">显示行数</param>
        /// <param name="sortField">排序字段</param>
        /// <param name="asearch">查询条件</param>
        /// <param name="search">详细查询条件</param>
        /// <param name="aId">活动id</param>
        /// <param name="awardsID">奖项id</param>
        /// <param name="jId">奖池id</param>
        /// <param name="uId">用户id</param>
        /// <returns></returns>
        public JsonResult GetTheWinningList(string sortField, string sortOrder, string asearch, int pageIndex = 1, int pageSize = 10, int aId = 0, int awardsID = 0, int jId = 0, int uId = 0)
        {
            PagerModel pm = new PagerModel();
            string where = " 1=1 ";
            if (aId != 0)
            {
                where += " and t.ActivityID=" + aId;
            }
            if (awardsID != 0)
            {
                where += " and t.AwardsID=" + awardsID;
            }
            if (jId != 0)
            {
                where += " and j.id=" + jId;
            }
            if (uId != 0)
            {
                where += " and u.id=" + uId;
            }
            pm.StrCondition = where;
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = sortField;
            PagedList<Marketing_TheWinning> roleList  = _market.GetTheWinningList(ref pm, LogOnUser.ECode);
            return Json(roleList, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #endregion

        #region 添加奖池
        public int JackpotAdd(Marketing_Jackpot model)
        {
            if (model.Type != 2)
            {
                model.StartDate = null;
                model.EndDate = null;
            }
            model.ChangeLoginID = LogOnUser.UserID;
            model.ChangeLoginName = LogOnUser.LoginName;
            model.ViewDel = 0;
            model.ChangeDate = DateTime.Now;
            //默认停用
            model.ViewFlag = 0;
            model.ResidueNums = model.TotalNums;
            model.ResidueMoney = model.TotalMoney;
            model.EnterpriseId = LogOnUser.EnterpriseId;
            int reslut = _market.AddJackpot(model);
            return reslut;
        }

        #endregion

        /// <summary>
        /// 查询聚合流量套餐
        /// </summary>
        /// <returns></returns>
        public JsonObject getFlowTable()
        {
            return DataApi.GetFlowTable();
        }
        /// <summary>
        ///  获取奖池model
        /// </summary>
        /// <returns></returns>
        public JsonResult GetJackpotModel(int jId)
        {
            return Json(_market.GetJackpotModel(jId));
        }



        #region 奖池授权
        /// <summary>
        /// 授权
        /// </summary>
        /// <returns></returns>
        public ActionResult Accredit(int ID)
        {
            Marketing_Jackpot Jackpot = _market.GetJackpotModel(ID);
            Hashtable ht = new Hashtable();
            Jackpot.ChangeDate = DateTime.Now;
            Jackpot.Id = ID;
            Jackpot.ViewFlag = Jackpot.ViewFlag == 0?1:0;
            ht.Add("flag",Jackpot.ViewFlag);
            bool b;
            //启用  剩余数量必须大于0
            if (Jackpot.ViewFlag == 1 && Jackpot.ResidueNums <= 0)
                b = false;
            else
                b=_market.Accredit(Jackpot);
         
            ht.Add("b",b);
            return Json( ht,JsonRequestBehavior.AllowGet);
        }
        #endregion

        #endregion

        #region 添加 活动

        #region 根据活动编号 中奖项
        /// <summary>
        /// 根据活动编号 中奖项
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAwards(int Aid)
        {
            List<Marketing_Awards> list = _market.GetAwards_Aid(Aid);
            Marketing_Awards roleList = getRandomAwards(list);
            Marketing_Jackpot jmodel = new Marketing_Jackpot();
            Hashtable ht = new Hashtable();
            ht.Add("Denomination", roleList.Denomination);
            ht.Add("EnterpriseName", roleList.EnterpriseName);
            ht.Add("Congrats", roleList.Congrats);
            ht.Add("ID", roleList.Id);
            return Json(ht, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 编辑活动 显示数据
        public JsonResult GetActivityDate(int Aid)
        {
            Marketing_Activity Activity = _market.GetActivityModel(Aid);
            List<Marketing_Awards> Awards = _market.GetAwards_Aid(Aid);
            Hashtable ht = new Hashtable();
            ht.Add("ActivityModle", Activity);
            ht.Add("Awards", Awards);
            return Json(ht, JsonRequestBehavior.AllowGet);
        }
        #endregion

        /// <summary>
        /// 添加奖项
        /// </summary>
        /// <param name="submitData">表单数据JSON字符串</param>
        /// <returns></returns>
        public void AwardsAdd(Marketing_Awards model)
        {
            model.ViewDel = 0;
            model.EnterpriseId = LogOnUser.EnterpriseId;
            if (model.type == 1 && model.type == 0)
            {
                model.Denomination = 0;
            }
            _market.InsertAwards(model);
        }

        /// <summary>
        /// 添加活动
        /// </summary>
        /// <param name="activity"></param>
        /// <param name="delivery"></param>
        /// <param name="AwardsData"></param>
        /// <param name="webInfo"></param>
        /// <returns></returns>                  
        public JsonResult ActivityAdd(Marketing_Template template, Marketing_Activity activity, Marketing_Delivery delivery, List<Marketing_Awards> awardsList, Marketing_ActivityInfo webInfo)
        {
            try
            {
                activity.ChangeDate = DateTime.Now;
                activity.ChangeLoginID = LogOnUser.UserID;
                activity.ChangeLoginName = LogOnUser.LoginName;
                activity.ViewDel = 0;
                activity.EnterpriseId = LogOnUser.EnterpriseId;
                activity.Batch = activity.Batch.TrimEnd(',');
                //派奖方式
                if (delivery.ID == 0) activity.DeliveryId = _market.AddDelivery(delivery);
                else _market.UpdateDelivery(delivery);                    //活动编辑
               
                //默认停用
                activity.ViewFlag = 0;
                //活动详情 
                if (string.IsNullOrWhiteSpace(webInfo.ID)) activity.ActivityInfoID = _market.AddActivityInfo(webInfo);
                else _market.UpdateActivityInfo(webInfo);
                //活动模板
                if (template.ID == 0) activity.TemplateID = TemplateSave(template);
                else _market.UpdateTemplate(template);
                //奖品设置
                Marketing_Jackpot j;
                foreach (Marketing_Awards awards in awardsList)
                {
                    awards.ViewDel = 0;                                              
                    awards.EnterpriseId = LogOnUser.EnterpriseId;
                    awards.ResidueNums = awards.TotalNums;
                     
                    j = _market.GetJackpotModel(awards.JackpotID);
                    awards.TotalMoney = j.Denomination * (int)awards.TotalNums;
                    awards.ResidueMoney = awards.TotalMoney;
                    activity.PredictMaxMoney += awards.PredictMaxMoney = Convert.ToDecimal(awards.TotalNums * j.MaxDenomination);
                    activity.PredictMinMoney += awards.PredictMinMoney = Convert.ToDecimal(awards.TotalNums * j.MinDenomination);
                }
                //活动信息
                if (activity.Id == 0 ) activity.Id = _market.AddActivity(activity);
                else _market.UpdActivity(activity);
                awardsList.ForEach(p => { p.ActivityId = activity.Id; });

                _market.AwardsAddorUpd(awardsList);
                return Json(true);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        /// <summary>
        /// 活动模板页保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int TemplateSave(Marketing_Template model)
        {
            int Tid = _market.TemplateSave(model);
            return Tid;
        }

        /// <summary>
        /// 读取活动模板页
        /// </summary>
        /// <param name="aId"></param>
        /// <returns></returns>
        public ActionResult GetTemplate(int aId = 0)
        {
            var model = _market.GetTemplateByAid(aId);
            if (model == null) return Json("");
            return Json(model);
        }

        #region 下拉框绑定
        /// <summary>
        /// 奖池下拉框 type: 1 红包 2 优惠券 3流量包
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult JackpotBox(string type)
        {
            if (string.IsNullOrEmpty(type)) type = "0";
            List<Marketing_Jackpot> list = _market.JackpotBox(type, LogOnUser.EnterpriseId);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #endregion

        #region 活动管理

        /// <summary>
        /// 分页 活动
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">显示行数</param>
        /// <param name="sortField">排序字段</param>
        /// <param name="sortOrder">升 降 序</param>
        /// <param name="key">查询条件</param>
        /// <param name="search">详细查询条件</param>
        /// <returns></returns>
        public ActionResult GetActivtiesList(string sortField, string sortOrder, string Asearch, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = sortField + " " + sortOrder;
            pm.StrCondition = " EnterpriseId="+LogOnUser.EnterpriseId;
        
        
            if (Asearch != "" && Asearch != null)
            {
                pm.StrCondition += "  AND Title like '%" + Asearch + "%' ";
            }
            var roleList = _market.GetActivityList(ref pm, Asearch, LogOnUser.ECode);

            return Json(roleList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 启用  禁用  活动
        /// </summary>
        /// <param name="Aid">活动ID</param>
        /// <param name="Flag">启用1 禁用 0</param>
        /// <returns>1是成功！ </returns>
        public decimal IsState(int Aid, int Flag)
        {
            Marketing_Activity model = new Marketing_Activity();
            model.ChangeLoginID = LogOnUser.UserID;
            model.ChangeLoginName = LogOnUser.LoginName;
            model.ChangeDate = DateTime.Now;
            model.Id = Aid;
            if (Flag == 1)
            {
                model.ViewFlag = 0;//禁用
                _market.updateMoneyOfNot(Aid);
            }
            else
            {        
                model.ViewFlag = 1;//启用
                _market.updateMoneyOfOk(Aid); 
            }
            return _market.UpdActivity(model);
           
        }

        /// <summary>
        /// 活动删除
        /// </summary>
        /// <returns></returns>
        public int ActivityDel(int Aid)
        {
            Marketing_Activity model = _market.GetActivityModel(Aid);
            model.ViewDel = 1;
            return _market.UpdActivity(model);
             
        }

    /// <summary>
        /// 检查是否绑定微信信息
    /// </summary>
    /// <param name="AId">活动ID</param>
    /// <param name="Type">类型  1 为启用 2为预览</param>
    /// <returns></returns>
        public JsonResult CheckIsbindWXSMS(int AId,int Type)
        {
            int wx = _configManager.CheckWXServices(LogOnUser.EnterpriseId);
            int sms = _configManager.CheckSMSServices(LogOnUser.EnterpriseId);
            List<Marketing_Awards> list= _market.GetAwards_Aid(AId);
            Boolean b=true;
            Hashtable ht = new Hashtable();
            if (Type==1)
            {
            foreach (var item in list)
            {
                Marketing_Jackpot model= _market.GetJackpotModel(  item.JackpotID );
                if (model.ResidueNums<item.TotalNums || model.ResidueMoney<item.TotalMoney)
	            {
		          b=false;
                  ht.Add("jName",model.Name);
                }
            }
            }
            ht.Add("state", b);
            ht.Add("wx",wx);
            ht.Add("sms",sms);
            return Json(ht);
        }

        #endregion

        public JsonResult DelJackpot(int Id)
        {
            Hashtable ht = new Hashtable();
            int count = _market.JackpotBindActivity(Id);
            if (count>=1)      //已经绑定了活动
            {
                ht.Add("state",1);
                ht.Add("count",count);
                return Json(ht,JsonRequestBehavior.AllowGet);
            }
            Marketing_Jackpot model = _market.GetJackpotModel(Id);
            if (model.ViewFlag==1)   //已启用
            {
                ht.Add("state",2);
                return Json(ht,JsonRequestBehavior.AllowGet);
            }
            model.ViewDel = 1;
            int result = _market.UpdJackpot(model);
            ht.Add("state", 3);
            ht.Add("count", result);
            return Json(ht, JsonRequestBehavior.AllowGet);
        }


        #region 用户管理

        //送红包
        public ActionResult HongBaoOK(Marketing_TheWinning model)
        {
            try
            {                      
                var list = _market.GetMarketingList(model.UserIds, LogOnUser.ECode);
                var wxConfigmodel = _configManager.GetwxBindModel(LogOnUser.EnterpriseId);
                foreach (var item in list)
                {
                    WX_Config wxConfig = new WX_Config();
                    wxConfig.AppId = wxConfigmodel.AppId;
                    wxConfig.AppSecret = wxConfigmodel.AppSecret;
                    wxConfig.CredentialPwd = wxConfigmodel.CredentialPwd;
                    wxConfig.CredentialAddress = wxConfigmodel.CredentialAddress;
                    wxConfig.mchid = wxConfigmodel.mchid;
                    //企业支付
                    WXApi _wxAPI = new WXApi();
                    
                    bool result = _wxAPI.EnterprisePayUser(item.OpenID, model.Denomination, wxConfig, model.Remark,UserIp);
                    if (!result) return Json(false);
              
                    model.ActivityID = 0;
                    model.UserID = item.ID;
                    model.AwardsID = 0;
                    model.Time = DateTime.Now;
                    model.Groupid = EnumManagement.GetEnumValue( EnumTheWinningGroup.hongBao) ; 
                    model.State =EnumManagement.GetEnumValue(  EnumTheWinningState.GetAwardSucceed); //发放成功
                    model.JiaMiCode =LogOnUser.LoginName+"_"+model.Code;
                    if (!_dbh.TabExists("marketing", "Marketing_TheWinning" + LogOnUser.ECode))
                    {
                        _the.CreateTheWinningTable("Marketing_TheWinning" + LogOnUser.ECode);        
                    }
                    _market.AddWinning(model, LogOnUser.ECode);
                }
                return Json(true);
            }
            catch (Exception ex)
            {
                return Json(false);
            }

        }

        //流量充值套餐
        public ActionResult GiveDataOk(Marketing_TheWinning model)
        {
            var list = _market.GetMarketingList(model.UserIds, LogOnUser.ECode);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.Phone))
                {
                    //检测号码支持的流量套餐
                    string phoneInfo = DataApi.GetPhoneInfo(item.Phone);
                    var result = ((JObject)JsonConvert.DeserializeObject(phoneInfo))["result"].ToString();
                    var company = ((JObject)JsonConvert.DeserializeObject(result))["company"].ToString();
                    string isTrue = string.Empty;
                    model.Code = FormCode.RechargeData();//充值流量订单号
                    if (company == "电信")
                    {
                     isTrue = DataApi.GetRequest2(item.Phone, model.DataID3_DX.Value, model.Code);
                         model.Data = model.Data_DX;
                         model.DataId = model.DataID3_DX.Value;
                         model.DataType = 1;
                    }
                    else if (company == "联通")
                    {
                         isTrue = DataApi.GetRequest2(item.Phone, model.DataID1_LT.Value, model.Code);
                        model.Data = model.Data_LT;
                        model.DataId = model.DataID1_LT.Value;
                        model.DataType = 3;
                    }
                    else if (company == "移动")
                    {
                         isTrue = DataApi.GetRequest2(item.Phone, model.DataID2_YD.Value, model.Code);
                         model.DataId = model.DataID2_YD.Value;
                         model.Data = model.Data_YD;
                         model.DataType = 2;
                    }
                    //添加记录
                    model.ActivityID = 0;
                    model.AwardsID = 0;
                    model.BatchID = 0;
                    model.Groupid = EnumManagement.GetEnumValue( EnumTheWinningGroup.liuliang);
                    model.UserID = LogOnUser.UserID;
                    model.Time = DateTime.Now;
                    model.State = EnumManagement.GetEnumValue( EnumTheWinningState.GetAwardSucceed);//已领取
                    if (isTrue != "true") return Json(isTrue);
                    model.Remark = isTrue;
                    if (!_dbh.TabExists("marketing", "Marketing_TheWinning" + LogOnUser.ECode))
                    {
                        _the.CreateTheWinningTable("Marketing_TheWinning" + LogOnUser.ECode);
                    }
                    _market.AddWinningOfData(model, LogOnUser.ECode);
                }
                else
                {
                  //  return Json("电话号码为空");
                }
            }
            return Json("true");
        }

        //获取用户中奖记录
        public ActionResult GetUserDealList(string sortField, string sortOrder, string Asearch,string uid, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = sortField + " " + sortOrder;
            pm.StrCondition = " u.ID="+uid;                           
            if (Asearch != "" && Asearch != null)
            {
                pm.StrCondition += " and (a.Title like '%" + Asearch + "%' or t.Remark like '%" + Asearch + "%' or code like '%" + Asearch + "%') ";
            }
           var roleList = _market.GetUserDealList(ref pm, LogOnUser.ECode);
            foreach (Marketing_TheWinning item in roleList.PageData)
            {
                if (item.Groupid!=null && Enum.IsDefined(typeof(EnumTheWinningGroup), item.Groupid))
                {
                    item.GroupName = EnumManagement.getEnumDisplay((EnumTheWinningGroup)Enum.ToObject(typeof(EnumTheWinningGroup), item.Groupid));
               
                }
               
            }
            return Json(roleList, JsonRequestBehavior.AllowGet);
        }

        #endregion

      
    }
}